// jqueryq全局扩展 
$(function() {
	var toastTimer = null;
	$.extend({
		confirm: function(params, callback, cancelCallback) {
			var defaultOpt = {
				modalClass: 'confirm-modal-common',
				width: '', 
				title: '提示',
				msg: '',
				cancelText: '取消',
				confirmText: '确定',
				cancel: function() {
					$(this).parents('.modal').addClass('hide');
				},
				confirm: function() {
					$(this).parents('.modal').addClass('hide');
				}
			};

			if (typeof params === 'string') {
				params = {
					msg: params,
					confirm: callback || defaultOpt.callback,
					cancel: cancelCallback || defaultOpt.callback,
				};
			}
			var opt = $.extend({}, defaultOpt, params),
				confirmModal = $('.' + opt.modalClass);
			// console.log(opt,confirmModal);
			var hideCancel = opt.cancelText ? '' : 'hide-important';


			if (confirmModal.length <= 0) {
				// console.log(1) 
				var confirmHtml = '<div class="modal confirm-modal ' + opt.modalClass + '">' +
					'<div class="modal-mask"></div>' +
					'<div class="modal-content">' +
					'<div class="modal-header">' +
					'<i class="iconfont" data-dismiss="modal">&#xe63d;</i>' +
					'<div class="modal-title">' + opt.title + '</div>' +
					'</div>' +
					'<div class="modal-body">' +
					opt.msg +
					'</div>' +
					'<div class="modal-footer">' +
					'<button type="button" class="hw-btn modal-confirm-btn" data-dismiss="modal">' + opt.confirmText + '</button>' +
					'<button type="button" class="hw-btn hw-default-btn modal-cancel-btn ' + hideCancel + '" data-dismiss="modal">' + opt.cancelText + '</button>' +
					'</div>' +
					'</div>' +
					'</div>';
				$('body').append(confirmHtml);

				setTimeout(function() {
					confirmModal = $('.' + opt.modalClass);
					confirmModal.removeClass('hide').show();
				}, 20);

			} else {
				console.log(2)
				confirmModal.removeClass('hide').show().find('.modal-body').html(opt.msg);
				confirmModal.show();
			}

			setTimeout(function() {
				$('.modal-confirm-btn').unbind('click').bind('click', function() { 
					if (opt.confirm) {
						opt.confirm();
						$(this).parents('.modal').addClass('hide');
					}
				});

				$('.modal-cancel-btn').unbind('click').bind('click', function() { 
					if (opt.cancel) {
						opt.cancel();
						$(this).parents('.modal').addClass('hide');
					}
				});
			}, 20);

		},
		alert: function(params, cb) {
			var elem = $('.hw-alert'),
				time = 1500;

			if (toastTimer) {
				clearTimeout(toastTimer);
			}
			
			if (elem.length > 0) {
				elem.fadeIn().find('.hw-container').text(params);
			} else {
				elem = document.createElement('div');
				elem.className = 'hw-alert';
				elem.innerHTML = '<div class="hw-mask"></div><div class="hw-container">' + params + '</div>';
				elem.style.display = 'block';
				$('body').append(elem);
				elem = $(elem);
			}
			
			toastTImer = setTimeout(function() {
				elem.fadeOut();
				if (cb && typeof cb == 'function') {
					cb();
				}
			}, time); 
		}
	});

	// jquery实例扩展
	$.fn.extend({
		modal: function(hide) {
			if (hide == 'hide') {
				$('body').css({
					'overflow': 'auto'
				});
				$('body, .modal').css({
					'padding-right': 0
				});
				$(this).fadeOut(function() {
					$('.confirm-modal').remove();
				});
				return;
			}
			$('body').css({
				'overflow': 'hidden'
			});
			// 有滚动条
			if ($(window).height() < $(document).height()) {
				$('body, .modal').css({
					'padding-right': '17px'
				});
			}
			$(this).fadeIn();
		},

		/**
		 * ajax 提交表单
		 * @param  {[DOM]}   form     [要提交的表单]
		 * @param  {Function} callback [ajax成功之后的回调]
		 * @return {[type]}            [description]
		 */
		submitForm: function( successCb, errorCb) {
			var form = $(this),
				btnSelector = form.data('submit'), // 触发表单提交的按钮选择器
				subBtn = null;

			if (successCb && typeof successCb != 'function') {
				subBtn = successCb;
			}else if (btnSelector) {
				subBtn = $(btnSelector);
			} else {
				subBtn = form.find('button[type="submit"]');
			}
		 
			subBtn.prop('disabled', true);
			var options = {  
			   success: success,      //提交后的回调函数  
			   error: error, 
			   dataType: 'json',           //html(默认), xml, script, json...接受服务端返回的类型  
			   clearForm: false,          //成功提交后，清除所有表单元素的值  
			   resetForm: false,          //成功提交后，重置所有表单元素的值  
			   timeout: 10000               //限制请求的时间，当请求大于10秒后，跳出请求  
			};

			function success(json) {   
				var msg = '';
				if (json.code == 1||json.code==20000 ) {
					msg = json.msg || json.message || '';
					msg = '成功';
					$.alert(msg, 'success');

					// 如果successCb存在， 页面不跳转， 如需跳转， 在successCb里面跳转
					if (successCb || typeof successCb == 'function') {
						successCb(json);
						subBtn.prop('disabled', false); 
					} else {
						if(json.url){
							setTimeout(function() {
								window.location.href = json.url;
							}, 1000);
						}else{
							setTimeout(function() {
								window.location.reload();
							}, 1000);
						}
						
					}
				} else {
					subBtn.prop('disabled', false);
					if (errorCb) {
						errorCb(json);
					} else {
						msg = json.msg || json.message || '保存失败';
						$.alert(msg, 'error');
					}			
				}
			}

			function error() {  
				$.alert('保存失败', 'error');
				subBtn.prop('disabled', false);
			}

			$(form).ajaxSubmit(options);
		}
	});
});